<script setup lang="ts">
import { useAppStore, useControllerStore } from '@/store';
import Tools, { IShoppingCartDiscountResult } from '../../../utils/tools';
import useToast from '@/hooks/useToast';
import useModal from '@/hooks/useModal';
import { navigate } from '@/utils/navigate';

interface IState {
  show: boolean;
  shoppingCart: IProductInformation[];
  price: number;
  favorablePrice: number;
  shoppingCartDiscount: IShoppingCartDiscountResult[];
}

const store = useAppStore();
const props = defineProps<{ show?: boolean }>();
const state = reactive<IState>({ show: props.show || false, shoppingCart: store.$state.shoppingCart, price: 0, favorablePrice: 0, shoppingCartDiscount: [] });
const { showToast } = useToast();
const { showModal } = useModal();

onMounted(() => {
  const invalidProduct: string[] = [];
  state.shoppingCart.forEach((item) => {
    const hasSell = Tools.hasProductInSaleTime(item);
    if (!hasSell) {
      invalidProduct.push(item.name);
      store.removeShoppingCart(item.goodsId);
    }
  });
  if (invalidProduct.length > 0) showToast(invalidProduct.toString().replace(/,/g, '-') + '不在可售时间，已从购物车中删除');
  state.shoppingCartDiscount = Tools.calculateShoppingCartDiscount(state.shoppingCart).results;
  state.price = Tools.calculateShoppingCartDiscount(state.shoppingCart).totalPrice;
  state.favorablePrice = Tools.calculateShoppingCartDiscount(state.shoppingCart).totalDiscountPrice;
});

onUnmounted(() => {
  unsubscribe();
});

// store全局监听
const unsubscribe = store.$subscribe((mutation, storeState) => {
  if (Array.isArray(mutation.events)) return;
  if (mutation.events.key === 'shoppingCart') {
    state.shoppingCart = storeState.shoppingCart;
    state.shoppingCartDiscount = Tools.calculateShoppingCartDiscount(storeState.shoppingCart).results;
    state.price = Tools.calculateShoppingCartDiscount(storeState.shoppingCart).totalPrice;
    state.favorablePrice = Tools.calculateShoppingCartDiscount(storeState.shoppingCart).totalDiscountPrice;
  }
});

// 计算匹配折扣属性
const calculationProductDiscount = (item: IProductInformation): IShoppingCartDiscountResult | undefined => {
  return state.shoppingCartDiscount.find((_item) => (item.goodsType === 2 ? _item.sku === item.sku : _item.variantId === item.variantId));
};

// 产品购物车加减
const handleOperationProductToShoppingCart = (type: 'add' | 'remove', data: IProductInformation) => {
  if (data.sku) {
    store.updateShoppingCartSku({ type, data: { ...data, nums: 1 } });
  } else {
    store.updateShoppingCart({ type, data });
  }
};

// 清空购物车
const handleEmptyShoppingCart = () => {
  showModal('确定清空购物车吗？', {
    showCancel: true,
    success: (res) => {
      if (res.confirm) {
        store.removeShoppingCart(undefined);
      }
    },
  });
};
</script>

<template>
  <view class="h-50px bg-white w-screen pos-relative" :class="useControllerStore().$state.productInformation ? 'z-99' : 'z-999'" :style="{ paddingBottom: store.$state.systemInfo.safeAreaInsets!.bottom + 'px' }">
    <van-divider hairline custom-style="margin: 0" />
    <view class="h-full w-full py-4px px-12px box-border flex justify-between items-center">
      <view class="flex flex-1 h-full" @click="state.show = !state.show">
        <view class="w-42px h-full rounded-50% c-bg flex justify-center items-center pos-relative">
          <i class="i-entypo:shopping-bag text-white text-24px" />
          <view v-if="Tools.getShoppingCartProductQuantity(state.shoppingCart) > 0" class="pos-absolute top-[-3px] right-[-6px] bg-red text-white w-20px h-20px rounded-50% flex justify-center items-center">{{ Tools.getShoppingCartProductQuantity(state.shoppingCart) }}</view>
        </view>
        <view class="ml-20px flex-col flex justify-center">
          <view class="text-red">
            ¥<text class="text-20px fw-bold ml-4px">{{ state.price }}</text>
          </view>
          <view class="c-text-color-grey c-text-12" v-if="state.favorablePrice > 0">优惠¥ {{ state.favorablePrice }}</view>
        </view>
      </view>
      <view class="h-90% c-br c-bg flex items-center justify-center text-white px-30px c-text-16" v-if="Tools.getShoppingCartProductQuantity(state.shoppingCart) > 0" @click="navigate({ url: '/subcontract/home/submitOrder/index' })">去结算</view>
      <view class="h-90% c-br bg-#9C9C9EFF flex items-center justify-center text-white px-30px c-text-16" v-else>去选购</view>
    </view>
  </view>
  <van-popup :show="state.show" round position="bottom" @close="state.show = false">
    <view class="bg-white mb-50px c-pd">
      <view class="flex justify-between">
        <text>购物车</text>
        <view @click="handleEmptyShoppingCart">
          <i class="i-mdi:trash-can-outline" />
          <text class="c-text-color-grey c-text-12 ml-4px">清空购物车</text>
        </view>
      </view>
      <van-divider hairline custom-style="margin: 12px 0" />
      <scroll-view scroll-y enhanced :show-scrollbar="false" class="overflow-hidden min-h-200px max-h-400px">
        <template v-for="(item, index) in state.shoppingCart" :key="index">
          <view class="flex mb-8px">
            <view class="w-80px h-80px c-br overflow-hidden">
              <image class="w-full h-full" :src="item.mainImage" lazy-load mode="aspectFill" />
            </view>
            <view class="pl-8px box-border overflow-hidden flex-1 flex flex-col justify-between">
              <view class="flex items-start">
                <view class="flex-1 c-text-ellipsis-2 w-full fw-bold">
                  {{ item.name }}
                </view>
                <view v-if="item.visitFlag !== 0" class="ml-4px c-text-8 px-4px py-2px rounded-4px border-1px border-#999999 border-solid c-text-color-grey">服务上门</view>
              </view>
              <view class="c-text-color-grey c-text-ellipsis-2 my-4px" v-if="item.goodsType === 1 || item.goodsType === 15"> {{ item.sku ? item.sku.replace(/:/g, '、') : '' }}</view>
              <view class="c-text-color-grey c-text-ellipsis-2 my-4px" v-if="item.goodsType === 2"> {{ item.sku ? item.sku.replace(/___|(\|\|\|)/g, '、') : '' }}</view>
              <template v-if="calculationProductDiscount(item)">
                <view v-if="(calculationProductDiscount(item) as IShoppingCartDiscountResult).activeCount > 0 && (calculationProductDiscount(item) as IShoppingCartDiscountResult).salePriceCount > 0">
                  <text class="fw-bold text-red c-text-16">¥{{ (calculationProductDiscount(item) as IShoppingCartDiscountResult).salePrice }}</text>
                  <text class="c-text-color-grey c-text-12 ml-8px">原价 x{{ (calculationProductDiscount(item) as IShoppingCartDiscountResult).salePriceCount }}</text>
                </view>
              </template>
              <view class="flex justify-between">
                <view class="flex items-center" v-if="calculationProductDiscount(item)">
                  <text class="fw-bold text-red c-text-16">
                    ¥{{ (calculationProductDiscount(item) as IShoppingCartDiscountResult).activeCount ? (calculationProductDiscount(item) as IShoppingCartDiscountResult).activePrice : (calculationProductDiscount(item) as IShoppingCartDiscountResult).salePrice }}
                  </text>
                  <text class="text-red c-text-12 ml-8px" v-if="(calculationProductDiscount(item) as IShoppingCartDiscountResult).activeCount > 0">
                    {{ (((calculationProductDiscount(item) as IShoppingCartDiscountResult).activePrice / (item.sku ? item.salePrice : item.price)) * 10).toFixed(2) }}折，限{{ (calculationProductDiscount(item) as IShoppingCartDiscountResult).maxNum }}份 x{{
                      (calculationProductDiscount(item) as IShoppingCartDiscountResult).activeCount
                    }}
                  </text>
                </view>
                <view class="flex items-center">
                  <template v-if="state.shoppingCart.find((_item) => _item.goodsId === item.goodsId)">
                    <i class="i-gg:remove c-color c-text-16" @click="handleOperationProductToShoppingCart('remove', item)" />
                    <text class="mx-8px fw-bold c-text-14" v-if="!item.sku">{{ state.shoppingCart.find((_item) => _item.goodsId === item.goodsId)?.nums }}</text>
                    <text class="mx-8px fw-bold c-text-14" v-else>{{ state.shoppingCart.find((_item) => _item.goodsId === item.goodsId && _item.sku === item.sku)?.nums }}</text>
                  </template>
                  <i class="i-icon-park-solid:add-one c-color c-text-16" @click="handleOperationProductToShoppingCart('add', item)" />
                </view>
              </view>
            </view>
          </view>
          <van-divider v-if="index !== state.shoppingCart.length - 1" />
        </template>

        <van-empty v-if="state.shoppingCart.length === 0" description="暂无数据" />
      </scroll-view>
    </view>
  </van-popup>
</template>
